<?php

/**
 * This page removes all expired servers (servers who didn't send a heartbeat in PING_TIMEOUT seconds) from the internet list
 * 
 * @author Matthias Van Eeghem <matthias@van-eeghem.com>
 * @copyright Copyright (c) 2012, Matthias Van Eeghem
 */

 // We need these defines for the MySQL details
require_once('Defines.php');

// PING_TIMEOUT specifies the maximum time between two pings
// After this amount, the server will be considered offline 
define('PING_TIMEOUT', 10);

// We read from the contents of LastMasterlistCheck.txt and convert it to an integer
// The contents of this file is the last time the masterlist was checked for offline servers
// It's saved an int in epoch time
$iLastCheck = intval(file_get_contents('LastMasterlistCheck.txt'));

// Get the current epoch time
$iNow = time();

// Before outputting any servers to the browser we want to make sure all servers we're outputting are actually still online.
// Since we do not want to check this every time MasterList.php is requested (it's
// not required and might stress the server), we only execute the check every 10 seconds
if($iNow > ($iLastCheck + PING_TIMEOUT))
{
	// First off all, we write the last time the check was executed to the file
	$fHandle = fopen('LastMasterlistCheck.txt', 'w');
	fwrite($fHandle, $iNow);
	fclose($fHandle);
	
	// Connect to the MySQL server
	$MySQLi = new mysqli(MySQL_Server, MySQL_User, MySQL_Password, MySQL_Database);
	
	// Select the columns IP and LastPing from all rows
	$preparedStatement = $MySQLi->prepare("SELECT IP, LastPing FROM MasterList");

	// Execute the query
	if($preparedStatement->execute())
	{
		// Get the result
		$aServers = $preparedStatement->get_result();
		
		// Close the query
		$preparedStatement->close();
		
		// Fetch a numeric array from the MySQL result set
		while ($aServerInfo = $aServers->fetch_array(MYSQL_NUM))
		{
			// Get the IP and LastPing (the last epoch time the server sent a ping command to the masterlist) for this server
			$sIP = $aServerInfo[0];
			$iLastPing = $aServerInfo[1];
		
			// If the current time is more than (last ping + PING_TIMEOUT), the server
			// has failed to send a PING command in time, we remove the server from the masterlist
			if($iNow > ($iLastPing + PING_TIMEOUT))
			{
				// Prepare an SQL DELETE statement and execute it
				$preparedDeleteStatement = $MySQLi->prepare("DELETE FROM MasterList WHERE IP=?");
				$preparedDeleteStatement->bind_param("s", $sIP);
				$preparedDeleteStatement->execute();
				$preparedDeleteStatement->close();
			}
		}
	}
}

?>